// utils/deviceDetector.js
class DeviceDetector {
    constructor() {
        this.deviceInfo = null;
    }

    /**
     * 获取完整的设备信息
     */
    async getDeviceInfo() {
        if (this.deviceInfo) {
            return this.deviceInfo;
        }

        const info = {
            // 基础设备信息
            userAgent: navigator.userAgent,
            platform: navigator.platform,
            language: navigator.language,

            // 屏幕信息
            screen: {
                width: screen.width,
                height: screen.height,
                availWidth: screen.availWidth,
                availHeight: screen.availHeight,
                colorDepth: screen.colorDepth,
                pixelDepth: screen.pixelDepth,
                devicePixelRatio: window.devicePixelRatio || 1
            },

            // 内存信息（如果可用）
            memory: this.getMemoryInfo(),

            // GPU信息
            gpu: await this.getGPUInfo(),

            // CPU信息
            cpu: this.getCPUInfo(),

            // 网络信息
            network: await this.getNetworkInfo(),

            // 浏览器性能
            performance: this.getPerformanceInfo(),

            // 设备类型
            deviceType: this.getDeviceType(),

            // 电池信息（如果可用）
            battery: await this.getBatteryInfo()
        };

        this.deviceInfo = info;
        return info;
    }

    /**
     * 获取内存信息
     */
    getMemoryInfo() {
        if ('memory' in navigator) {
            return {
                deviceMemory: navigator.memory.deviceMemory || null,
                usedJSHeapSize: navigator.memory.usedJSHeapSize || null,
                totalJSHeapSize: navigator.memory.totalJSHeapSize || null,
                jsHeapSizeLimit: navigator.memory.jsHeapSizeLimit || null
            };
        }
        return null;
    }

    /**
     * 获取GPU信息
     */
    async getGPUInfo() {
        try {
            // WebGL信息
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');

            if (!gl) {
                return { webglSupported: false };
            }

            const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
            const vendor = debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR);
            const renderer = debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);

            return {
                webglSupported: true,
                webgl2Supported: !!canvas.getContext('webgl2'),
                vendor: vendor,
                renderer: renderer,
                version: gl.getParameter(gl.VERSION),
                shadingLanguageVersion: gl.getParameter(gl.SHADING_LANGUAGE_VERSION),
                maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
                maxViewportDims: gl.getParameter(gl.MAX_VIEWPORT_DIMS),
                maxRenderBufferSize: gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
            };
        } catch (error) {
            console.warn('Failed to get GPU info:', error);
            return { webglSupported: false, error: error.message };
        }
    }

    /**
     * 获取CPU信息
     */
    getCPUInfo() {
        return {
            cores: navigator.hardwareConcurrency || null,
            architecture: navigator.platform,
            // 通过性能测试估算CPU性能
            estimatedPerformance: this.estimateCPUPerformance()
        };
    }

    /**
     * 估算CPU性能
     */
    estimateCPUPerformance() {
        const start = performance.now();
        let result = 0;
        // 简单的计算密集型任务
        for (let i = 0; i < 100000; i++) {
            result += Math.sqrt(i) * Math.sin(i);
        }
        const duration = performance.now() - start;

        return {
            testDuration: duration,
            performance: duration < 10 ? 'high' : duration < 50 ? 'medium' : 'low'
        };
    }

    /**
     * 获取网络信息
     */
    async getNetworkInfo() {
        const networkInfo = {
            onLine: navigator.onLine,
            connectionType: null,
            effectiveType: null,
            downlink: null,
            rtt: null,
            saveData: null
        };

        // Network Information API
        if ('connection' in navigator) {
            const connection = navigator.connection;
            networkInfo.connectionType = connection.type;
            networkInfo.effectiveType = connection.effectiveType;
            networkInfo.downlink = connection.downlink;
            networkInfo.rtt = connection.rtt;
            networkInfo.saveData = connection.saveData;
        }

        // 网络速度测试（简化版）
        networkInfo.speedTest = await this.performSpeedTest();

        return networkInfo;
    }

    /**
     * 简单的网络速度测试
     */
    async performSpeedTest() {
        try {
            const startTime = performance.now();

            // 请求一个小的测试文件或接口
            const response = await fetch('/backcode/api/ping', {
                method: 'GET',
                cache: 'no-cache'
            });
            const endTime = performance.now();

            return {
                latency: endTime - startTime,
                status: response.status === 200 ? 'good' : 'poor'
            };
        } catch (error) {
            return {
                latency: null,
                status: 'poor',
                error: error.message
            };
        }
    }

    /**
     * 获取性能信息
     */
    getPerformanceInfo() {
        const perfInfo = {
            timing: null,
            memory: null,
            navigation: null
        };

        if ('performance' in window) {
            // 页面加载性能
            if (performance.timing) {
                const timing = performance.timing;
                perfInfo.timing = {
                    loadTime: timing.loadEventEnd - timing.navigationStart,
                    domReady: timing.domContentLoadedEventEnd - timing.navigationStart,
                    connectTime: timing.connectEnd - timing.connectStart
                };
            }

            // 内存使用
            if (performance.memory) {
                perfInfo.memory = {
                    usedJSHeapSize: performance.memory.usedJSHeapSize,
                    totalJSHeapSize: performance.memory.totalJSHeapSize,
                    jsHeapSizeLimit: performance.memory.jsHeapSizeLimit
                };
            }

            // 导航类型
            if (performance.navigation) {
                perfInfo.navigation = {
                    type: performance.navigation.type,
                    redirectCount: performance.navigation.redirectCount
                };
            }
        }

        return perfInfo;
    }

    /**
     * 判断设备类型
     */
    getDeviceType() {
        const ua = navigator.userAgent;
        const isMobile = /Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
        const isTablet = /iPad|Android(?!.*Mobile)/i.test(ua);
        const isDesktop = !isMobile && !isTablet;

        return {
            isMobile,
            isTablet,
            isDesktop,
            type: isMobile ? 'mobile' : isTablet ? 'tablet' : 'desktop'
        };
    }

    /**
     * 获取电池信息
     */
    async getBatteryInfo() {
        try {
            if ('getBattery' in navigator) {
                const battery = await navigator.getBattery();
                return {
                    charging: battery.charging,
                    level: battery.level,
                    chargingTime: battery.chargingTime,
                    dischargingTime: battery.dischargingTime
                };
            }
        } catch (error) {
            console.warn('Battery API not supported:', error);
        }
        return null;
    }

    /**
     * 获取简化的设备评分（用于快速判断）
     */
    getDeviceScore(deviceInfo) {
        let score = 0;
        const scores = {
            cpu: 0,
            memory: 0,
            gpu: 0,
            network: 0,
            device: 0
        };

        // CPU评分
        if (deviceInfo.cpu?.cores) {
            scores.cpu = Math.min(deviceInfo.cpu.cores * 10, 40);
        }
        if (deviceInfo.cpu?.estimatedPerformance?.performance === 'high') scores.cpu += 20;
        else if (deviceInfo.cpu?.estimatedPerformance?.performance === 'medium') scores.cpu += 10;

        // 内存评分
        if (deviceInfo.memory?.deviceMemory) {
            scores.memory = Math.min(deviceInfo.memory.deviceMemory * 5, 30);
        }

        // GPU评分
        if (deviceInfo.gpu?.webgl2Supported) scores.gpu += 20;
        else if (deviceInfo.gpu?.webglSupported) scores.gpu += 10;

        // 网络评分
        if (deviceInfo.network?.effectiveType === '4g') scores.network += 20;
        else if (deviceInfo.network?.effectiveType === '3g') scores.network += 10;
        if (deviceInfo.network?.speedTest?.latency < 100) scores.network += 10;

        // 设备类型评分
        if (deviceInfo.deviceType?.type === 'desktop') scores.device += 20;
        else if (deviceInfo.deviceType?.type === 'tablet') scores.device += 10;

        score = Object.values(scores).reduce((sum, s) => sum + s, 0);

        return {
            totalScore: score,
            breakdown: scores,
            level: score > 80 ? 'high' : score > 50 ? 'medium' : 'low'
        };
    }
}

// 导出单例
export default new DeviceDetector();